import { type FC, useRef } from 'react';
import { useUpdateEffect, useMemoizedFn } from 'ahooks';
import Carousel, { type ICarouselInstance } from 'react-native-reanimated-carousel';
import TabPage from './page';
import Resize from '../Resize';
import type { TabPageViewProps } from './types';
import styles from './styles';

const TabPageView: FC<TabPageViewProps> = (props) => {
  const { pages, page = 0, defaultPage = 0 } = props;
  const ref = useRef<ICarouselInstance>(null);

  const sliderToPage = useMemoizedFn(() => {
    const instance = ref.current!;
    if (instance.getCurrentIndex() !== page) {
      instance.scrollTo({
        index: page,
        animated: true,
        count: pages.length
      });
    }
  });

  const onScrollEnd = useMemoizedFn(
    (index: number) => {
      if (index !== page) {
        props.onChange?.(index);
      };
    }
  );

  useUpdateEffect(sliderToPage, [page]);

  return (
    <Resize style={styles.container}>
      {(e) => (
        <Carousel
          ref={ref}
          loop={false}
          data={pages}
          width={e.width}
          onScrollEnd={onScrollEnd}
          scrollAnimationDuration={300}
          defaultIndex={defaultPage}
          panGestureHandlerProps={{
            activeOffsetX: [-20, 20],
          }}
          renderItem={({ item, index }) => {
            const active = index === page;
            return (
              <TabPage active={active}>
                {item.page}
              </TabPage>
            );
          }}
        />
      )}
    </Resize>
  );
}

export default TabPageView;